<?php

class Mailer
{

    /**
     * default sender charset
     */
    CONST CHARSET = 'utf8';

    /**
     * @var Zend_Mail_Transport
     */
    protected $_transport = null;

    /**
     * @return Zend_Mail_Transport
     */
    protected function getTransport()
    {
        if (null == $this -> _transport)
        {
            // Get config
            $config = Agilet::loadConfig('mail');
            $mailConfig = array(
                'class' => 'Zend_Mail_Transport_Sendmail',
                'args' => array(),
            );

            // Get transport
            try
            {
                $args = (!empty($mailConfig['args']) ? $mailConfig['args'] : array());
                $r = new ReflectionClass($mailConfig['class']);

                $transport = $r -> newInstanceArgs($args);

                if (!($transport instanceof Zend_Mail_Transport_Abstract))
                {
                    $this -> _transport = false;
                }
                else
                {
                    $this -> _transport = $transport;
                }
            }
            catch( Exception $e )
            {
                $this -> _transport = false;
                throw $e;
            }
        }

        if (!($this -> _transport instanceof Zend_Mail_Transport_Abstract))
        {
            return null;
        }

        return $this -> _transport;
    }

    public function getPlugin($name)
    {

    }

    /**
     * send to mailer
     * @param string $name
     * @param string/array/int $receiver
     * @param array $data
     * @param bool $queue null
     * @return true/false
     */
    static public function send($receiver, $data = array(), $plugin = null, $queue = null, $config = null)
    {
        if (null == $queue)
        {
            $queue = FALSE;
        }

        if ($queue)
        {
            $item = Document::factory('core/mailqueue');
            $item -> receiver = $receiver;
            $item -> data = $data;
            $item -> config = $config;
            $item -> created_at = time();
            $item -> is_sent = false;
            $item -> plugin = $plugin;
            return $item -> save();
        }

        // process sended email
        return true;
    }

    protected function _send($receiver, $data = array(), $plugin = null, $config = null)
    {
        $mail = new Zend_Mail(self::CHARSET);

        $mail = $this -> create();

        $mail -> addTo($recipientEmail, $recipientName);

        $mail -> setFrom($fromAddress, $fromName);
        $mail -> setSubject($subject);
        $mail -> setBodyHtml($bodyHtml);

        // $mail -> setBodyText($bodyText);

        $mail -> send($this -> getTransport());
    }

}
